<template>
  <div class="crowdfunding-list">
    <!-- 页面标题和新增按钮 -->
    <div class="page-header">
      <h2>服装定制众筹</h2>
      <el-button type="primary" @click="handleAdd">发起众筹</el-button>
    </div>

    <!-- 项目列表 -->
    <el-table :data="projectList" stripe>
      <el-table-column prop="projectName" label="项目名称" />
      <el-table-column prop="description" label="项目描述" />
      <el-table-column label="众筹进度" width="250">
        <template #default="scope">
          <div>{{ scope.row.currentQuantity }}/{{ scope.row.targetQuantity }}件</div>
          <el-progress 
            :percentage="((scope.row.currentQuantity / scope.row.targetQuantity) * 100).toFixed(3)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="price" label="单价" width="100">
        <template #default="scope">
          ¥{{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="截止时间" width="180" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button 
            size="small" 
            type="primary"
            @click="handleOrders(scope.row)"
          >
            订单管理
          </el-button>
          <el-button 
            size="small"
            @click="handleEdit(scope.row)"
            :disabled="scope.row.status === 'completed'"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '发起众筹' : '编辑众筹'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="formData.projectName" />
        </el-form-item>
        <el-form-item v-if="dialogType === 'add'" label="商品id" prop="goodId">
          <el-input v-model="formData.goodId" />
        </el-form-item>
        <el-form-item label="目标件数" prop="targetQuantity">
          <el-input-number v-model="formData.targetQuantity" :min="1" />
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input-number v-model="formData.price" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item v-if="dialogType === 'add'" label="截止时间" prop="startTime">
          <el-date-picker
            v-model="formData.startTime"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD hh:mm:ss"
            value-format="YYYY-MM-DD hh:mm:ss"
          />
        </el-form-item>
        <el-form-item v-if="dialogType === 'add'" label="截止时间" prop="endTime">
          <el-date-picker
            v-model="formData.endTime"
            type="datetime"
            placeholder="选择截止时间"
            format="YYYY-MM-DD hh:mm:ss"
            value-format="YYYY-MM-DD hh:mm:ss"
          />
        </el-form-item>
        <el-form-item label="项目描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getFactoryInfoAPI } from '@/api/factory'
import { getCrowdfundingListAPI, addCrowdFundingAPI, editCrowdFundingAPI } from '@/api/crowdFunding'
import { useTokenStore } from '@/store/token';

// 用户信息
const tokenStore = useTokenStore()

const router = useRouter()

// 项目列表数据
const projectList = ref([])

// 众筹列表
async function getCrowdFundingList() {
  const factoryId = await (await getFactoryInfoAPI(tokenStore.user.userId)).data.factoryId
  console.log(factoryId)
  getCrowdfundingListAPI(factoryId).then(res => {
    if (res.code === 0) {
      console.log(res.data)
      projectList.value = res.data
    } else {
      ElMessage.error(res.message || '获取众筹列表失败')
    }
  })
}
getCrowdFundingList();

// 弹窗控制
const dialogVisible = ref(false)
const dialogType = ref('add') // add 或 edit
const formRef = ref(null)

// 表单数据
const formData = reactive({
  projectId: null,
  goodId: '',
  projectName: '',
  targetQuantity: 1,
  price: 0,
  description: '',
  startTime: '',
  endTime: ''
})

// 表单验证规则
const formRules = {
  projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  targetQuantity: [{ required: true, message: '请输入目标件数', trigger: 'blur' }],
  price: [{ required: true, message: '请输入单价', trigger: 'blur' }],
  endTime: [{ required: true, message: '请选择截止时间', trigger: 'blur' }]
}

// 状态样式
const getStatusType = (status) => {
  const statusMap = {
    funding: 'warning',   // 募集中
    success: 'success',   // 已达成
    failed: 'danger',     // 未达成
    completed: 'info'     // 已结束
  }
  return statusMap[status]
}

// 状态文本
const getStatusText = (status) => {
  const statusMap = {
    funding: '募集中',
    success: '已达成',
    failed: '未达成',
    completed: '已结束'
  }
  return statusMap[status]
}

// 新增按钮
const handleAdd = () => {
  dialogType.value = 'add'
  formData.projectId = null
  formData.goodId = ''
  formData.projectName = ''
  formData.targetQuantity = 1000
  formData.price = 0
  formData.description = ''
  formData.startTime = ''
  formData.endTime = ''
  dialogVisible.value = true
}

// 编辑按钮
const handleEdit = (row) => {
  dialogType.value = 'edit'
  formData.projectId = row.projectId
  formData.projectName = row.projectName
  formData.targetQuantity = row.targetQuantity
  formData.price = row.price
  formData.description = row.description
  dialogVisible.value = true
}

// 提交表单
const  handleSubmit = async() => {
  if (!formRef.value) return
  if (dialogType.value === 'add') {
    const factoryId = await (await getFactoryInfoAPI(tokenStore.user.userId)).data.factoryId
    let data = { projectName: formData.projectName, goodId: formData.goodId, targetQuantity: formData.targetQuantity, price: formData.price, startTime: formData.startTime, endTime: formData.endTime, description: formData.description, factoryId: factoryId }
    console.log('发起众筹,data: ', data)
    addCrowdFundingAPI(data).then(res => {
      if (res.code === 0){
        ElMessage.success('发起众筹成功')
      } else{
        ElMessage.error(res.message || '发起众筹失败,请重试')
      }
    })
    dialogVisible.value = false
  } else {
    let data = { projectId: formData.projectId, projectName: formData.projectName, targetQuantity: formData.targetQuantity, price: formData.price, description: formData.description }
    console.log('编辑众筹,data: ', data)
    editCrowdFundingAPI(data).then(res => {
      if (res.code === 0) {
        ElMessage.success('编辑众筹信息成功!')
      } else {
        ElMessage.error(res.message || '编辑众筹信息失败')
      }
    })
    dialogVisible.value = false
  }
  getCrowdFundingList();
}

// 查看订单
const handleOrders = (row) => {
  router.push(`/factory/projectOrders/${row.projectId}`)
}
</script>

<style scoped lang="scss">
.crowdfunding-list {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
}
</style>